// components/bug-type/index.js
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
import * as Storage from '../../utils/storage';
const $api = require('../../request/api').API;
const app = getApp();
Component({
	/**
	 * 组件的属性列表
	 */
	properties: {
		obj: {
			type: Object
		}
	},

	/**
	 * 组件的初始数据
	 */
	data: {
		show: false,
		goodsList: [],
		linkUrl: '',
		price: '',
		harvestAddressId: '',
		discountPrice: 0
	},
	observers: {
		async obj(val) {
			if (JSON.stringify(val) == '{}') return;
			let {
				eventId,
				goods,
				id,
				btnType,
				classifyIds,
				queryType,
				beeperId,
				orderSource,
				sourceId,
				linkUrl,
				addressInfo,
				btnName
			} = val;
			if (eventId == 11 || eventId == 12) {
				const {
					serverId,
					goodsId,
					thirdClassifyId,
					ruleId,
					goodsType,
					combineId
				} = goods;
				const {
					harvestAddressId
				} = addressInfo;
				if (goodsType !== 15) {
					if (harvestAddressId) {
						wx.navigateTo({
							url: '/subcontract/home/pages/submit/index?query=' + encodeURIComponent(JSON.stringify(val))
						});
						return;
					}
					// if(!combineId){
					//   let res = await $api.getFormInfo({serverIds:serverId,goodsIds:goodsId,thirdClassifyIds:thirdClassifyId,ruleIds:ruleId})
					//   res = res.data.data
					//   if(res){
					//     val.attr = res
					//     wx.navigateTo({
					//       url: '/pages2/pages/mall/submit/index?query='+encodeURIComponent(JSON.stringify(val)),
					//     })
					//     return
					//   }
					// }
				} else {
					this.setData({
						harvestAddressId: harvestAddressId
					})
				}

				this.activeTime(goods);
				this.judgeTimeout([goods]);
				console.log(goods, "goods")
				this.setData({
					show: true,
					goodsList: [goods],
					linkUrl: [...linkUrl].join(' ') || ''
				});
			} else if (eventId == 13 || eventId == 14) {
				wx.setStorageSync('shopCartData', JSON.stringify([]));
				wx.setStorageSync('formList', JSON.stringify([]));
				app.globalData['btnList.beeperId'] = beeperId;
				app.globalData['btnList.btnId'] = id;
				app.globalData['btnList.btnServerClassifyIds'] = classifyIds;
				app.globalData['btnList.queryType'] = queryType;
				app.globalData['btnList.btnType'] = btnType;
				// 详情页下单
				const {
					goodsId,
					beeperBtnId
				} = goods;
				let query = [];
				if (orderSource) query.push('orderSource=' + orderSource);
				if (sourceId) query.push('sourceId=' + sourceId);
				if (btnName) query.push('btnName=' + btnName);
				if (eventId == 13) {
					query.push('goodsId=' + goodsId + '&beeperBtnId=' + beeperBtnId);
					wx.navigateTo({
						url: '/subcontract/home/pages/goodsDetail/index?' + query.join('&')
					});
				} else if (eventId == 14) {
					// 结算页下单
					app.globalData.goodsList = [goods];
					query = query.length ? '?' + query.join('&') : '';
					wx.navigateTo({
						url: '/subcontract/home/pages/submitOrder/index' + query
					});
				}
			}
		}
	},
	/**
	 * 组件的方法列表
	 */
	methods: {
		// 判断哪些产品不在销售时间内
		judgeTimeout(goodsList) {
			goodsList.forEach(item => {
				let res = null;
				if (!item.goodsHours || (item.goodsHours && !item.goodsHours.length)) {
					return;
				}
				res = item.goodsHours.some(item => {
					let time = new Date();
					let begin = new Date();
					let end = new Date();
					const arr = item.beginHours.split(':').map(item => Number(item));
					const arr2 = item.endHours.split(':').map(item => Number(item));
					begin.setHours(arr[0]);
					begin.setMinutes(arr[1]);
					end.setHours(arr2[0]);
					end.setMinutes(arr2[1]);
					return time.getTime() > begin.getTime() && time.getTime() < end.getTime();
				});
				if (!res) {
					item.saleState = 0;
				}
			});
		},
		//需要判断是不是活动时间
		activeTime(val) {
			val = Array.isArray(val) ? val : [val]; //拼接一个数组好计算
			val.forEach(item => {
				if (!item.active) return;
				let {
					beginDate,
					endDate,
					activePrice
				} = item.active;
				beginDate = getDatetime(beginDate).getTime();
				endDate = getDatetime(endDate).getTime();
				let nowDate = new Date().getTime();
				if (nowDate > beginDate && nowDate < endDate) {
					item.activeDiscount = parseFloat(((activePrice / item.price) * 10).toFixed(2)) || 0.01;
				} else {
					item.activeDiscount = '';
				}
			});
		},
		priceInput(e) {
			let {
				value
			} = e.detail;
			const num = Number(value);

			// 输入有效性检查
			if (isNaN(num)) {
				value = '';
			} else if (num > 100000) {
				value = '';
				Toast.fail('只能是0.01到100000之间');
			} else if (value.includes('.') && value.split('.')[1].length > 2) {
				value = parseFloat(parseFloat(value).toFixed(2)).toString();
			}

			// 设置价格数据
			this.setData({
				price: value
			});

			// 实时计算折扣价格
			this.calculateDiscountPrice(value);
		},
		calculateDiscountPrice(value) {
			const {
				goodsList
			} = this.data;
			if (value && Number(value) >= 0.01) {
				const discountPrice = (goodsList[0].externalDiscount === 0) ?
					parseFloat(value).toFixed(2) :
					parseFloat((value * (goodsList[0].externalDiscount / 100)).toFixed(2));

				this.setData({
					discountPrice
				});
			} else {
				
				this.setData({
					discountPrice: 0 // 如果价格无效，清空折扣价格
				});
			}
		},
	
		addNum(e) {
			let {
				item: {
					nums
				},
				index
			} = e.currentTarget.dataset;
			const {
				goodsList
			} = this.data;
			goodsList[index].nums = ++nums;
			this.setData({
				goodsList
			});
		},
		subNum(e) {
			let {
				item: {
					nums
				},
				index
			} = e.currentTarget.dataset;
			const {
				goodsList
			} = this.data;
			goodsList[index].nums = nums <= 1 ? 1 : --nums;
			this.setData({
				goodsList
			});
		},
		async submitOrder() {
			const {
				goodsList,
				obj: {
					beeperId,
					id,
					btnName,
					orderSource,
					sourceId
				},
				price,
			} = this.data;
			let {
				variantId,
				nums,
				goodsType,
				stock,
				saleState,
				goodsHours,
				goodsId,
				combineId,
				externalDiscount
			} = goodsList[0];
			nums = nums == null ? 1 : nums
			if (!stock) {
				return Toast.fail('暂无库存');
			}
			if (saleState != 2 && goodsHours && goodsHours.length) {
				return Toast.fail('不在可售时间内');
			}

			await Dialog.confirm({
				title: '提示',
				message: '确定下单？',
				zIndex: '999'
			});
			let params = {
				beeperId,
				btnId: id,
				nums,
				openId: wx.getStorageSync(Storage.USER_OPEN_ID),
				harvestAddressId: this.data.harvestAddressId
			};
			// let harvestAddressId = await this.addressCpm.validate()
			// if (!harvestAddressId) return
			// params.harvestAddressId = harvestAddressId
			if (goodsType == 15) return this.premiumPriceSubmit({
				...params,
				variantId,
				amount: parseFloat(price)
			});

			if (combineId) {
				Object.assign(params, {
					combineId
				});
			} else {
				Object.assign(params, {
					variantId,
					goodsId,
					goodsType
				});
				if (orderSource) params.orderSource = orderSource;
				if (sourceId) params.sourceId = sourceId;
				if (btnName) params.btnName = btnName;
			}
			Toast.loading({
				message: '正在下单',
				forbidClick: true,
				mask: true,
				duration: 0
			});
			let res = await $api.simpleOrder(params);
			res = res.data.data;
			if (res) {
				Toast.clear();
				await wx.requestPayment({
					timeStamp: res.timeStamp,
					nonceStr: res.nonceStr,
					package: res.package,
					signType: res.signType,
					paySign: res.paySign
				});
			}
			Toast.success({
				message: '下单成功',
				forbidClick: true,
				mask: true
			});
			setTimeout(() => {
				app.globalData.beeperOrderId = beeperId;
				wx.switchTab({
					url: '/pages/order/index'
				});
			}, 2000);
			this.close();
		},
		// 差价下单
		async premiumPriceSubmit(params) {
			delete params.nums;
			if (!params.amount) return Toast.fail('请输入价格');
			Toast.loading({
				message: '正在下单',
				forbidClick: true,
				mask: true,
				duration: 0
			});
			let res = await $api.premiumOrder(params);
			Toast.clear();
			res = res.data.data;
			await wx.requestPayment({
				timeStamp: res.timeStamp,
				nonceStr: res.nonceStr,
				package: res.package,
				signType: res.signType,
				paySign: res.paySign
			});
			Toast.success({
				message: '下单成功',
				forbidClick: true,
				mask: true
			});
			setTimeout(() => {
				app.globalData.beeperOrderId = beeperId;
				wx.switchTab({
					url: '/pages/order/index'
				});
			}, 2000);
			this.close();
		},
		close() {
			this.setData({
				show: false,
				discountPrice: 0,
				price: ''
			});
		}
	}
});